//
//  EditRequirementViewController.m
//  Fangmm
//
//  Created by 阮琦 on 16/3/9.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "EditRequirementViewController.h"
#import "FilterRegionsViewController.h"
#import "FilterSortByViewController.h"

#import "ACMacros.h"
#import "AppDrawer.h"
#import "Utility.h"
#import "Constants.h"

#import "Requirement.h"
#import "HttpServer.h"

#import <TSMessages/TSMessageView.h>
#import <MobClick.h>

@interface EditRequirementViewController () <UITableViewDataSource, UITableViewDelegate, FilterRegionsViewDelegate, FilterSortByViewDelegate>

@end

@implementation EditRequirementViewController {
    FilterRegionsViewController *regionVC;
    FilterSortByViewController *rentVC;
    FilterSortByViewController *orderTimeVC;
    
    NSString *area;
    NSString *regionParam;
    NSString *districtParam;
    NSString *regionCodeParam;
    NSString *dayParam;
    NSString *priceParam;
    
    NSArray *rentArray;
    NSArray *orderTimeArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configureNavigationBar];
    [self configureTableView];
    Requirement *requirement = [Utility getObjectForKey:kRequirement];
    if (requirement.region == nil) {
        regionParam = @"";
    } else {
        regionParam = requirement.region;
    }
    if (requirement.district == nil) {
        districtParam = @"";
    } else {
        districtParam = requirement.district;
    }
    if (requirement.regionCode) {
        regionCodeParam = [NSString stringWithFormat:@"%d",requirement.regionCode];
    } else {
        regionCodeParam = @"";
    }
    if (requirement.day) {
        if (requirement.day == 7) {
            dayParam = @"7天内";
        } else if (requirement.day == 15) {
            dayParam = @"15天内";
        } else if (requirement.day == 30) {
            dayParam = @"30天内";
        } else if (requirement.day == 60) {
            dayParam = @"2个月内";
        } else {
            dayParam = @"7天内";
        }
    } else {
        dayParam = @"";
    }
    if (requirement.price == nil) {
        priceParam = @"";
    } else {
        priceParam = requirement.price;
    }
    // Do any additional setup after loading the view from its nib.
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"编辑需求页"];//("PageOne"为页面名称，可自定义)
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"编辑需求页"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - Configuring the view’s layout behavior
- (void)configureNavigationBar {
    self.title = @"租房需求";
    self.navigationItem.hidesBackButton = true;
    UIImage *backImage = [[UIImage imageNamed:@"back-18-36"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithImage:backImage style:UIBarButtonItemStyleDone target:self action:@selector(clickToDismiss:)];
    self.navigationItem.leftBarButtonItem = leftBarButton;
}

- (void)configureTableView {
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height - 20)];
    [self.view addSubview:self.tableView];
    [self.tableView setBackgroundColor:RGBACOLOR(240, 240, 240, 1)];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setBounces:false];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    CGFloat cellHeight = [self.tableView rectForRowAtIndexPath:indexPath].size.height;
    CGFloat cellWidth = [self.tableView rectForRowAtIndexPath:indexPath].size.width;
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(12, cellHeight - 0.5, cellWidth - 12, 0.5)];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [cell setTintColor:RGBACOLOR(119, 119, 119, 0.7)];
    [cell.textLabel setFont:[UIFont systemFontOfSize:15]];
    [cell.detailTextLabel setFont:[UIFont systemFontOfSize:15]];
    [cell.textLabel setTextColor:RGBACOLOR(71, 62, 58, 1)];
    [line setBackgroundColor:RGBACOLOR(119, 119, 119, 0.7)];
    if (row < 2) {
        [cell addSubview:line];
    }
    switch (row) {
        case 0:
            [cell.textLabel setText:@"目标区域"];
            [cell.detailTextLabel setText:[NSString stringWithFormat:@"%@ - %@",districtParam, regionParam]];
            break;
        case 1:
            [cell.textLabel setText:@"租金预算"];
            [cell.detailTextLabel setText:priceParam];
            break;
        case 2:
            [cell.textLabel setText:@"预住时间"];
            [cell.detailTextLabel setText:dayParam];
            break;

            
        default:
            break;
    }
    return cell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    switch (row) {
        case 0:
        {
            if (!regionVC) {
                regionVC = [[FilterRegionsViewController alloc]initWithNibName:@"FilterRegionsViewController" bundle:nil];
                regionVC.delegate = self;
            }
            [self presentViewController:regionVC animated:true completion:^{
            }];
        }
            break;
        case 1:
        {
            if (!rentVC) {
                rentVC = [[FilterSortByViewController alloc]initWithNibName:@"FilterSortByViewController" bundle:nil];
                rentVC.delegate = self;
                rentArray = @[@"¥800 - ¥1200", @"¥1200 - ¥1500", @"¥1500 - ¥2000", @"¥2000+"];
                rentVC.sourceDataArray = rentArray;
                
            }
            [self presentViewController:rentVC animated:true completion:^{
            }];
        }
            break;
        case 2:
        {
            if (!orderTimeVC) {
                orderTimeVC = [[FilterSortByViewController alloc]initWithNibName:@"FilterSortByViewController" bundle:nil];
                orderTimeVC.delegate = self;
            }
            orderTimeArray = @[@"7天内", @"15天内", @"30天内", @"2个月内"];
            orderTimeVC.sourceDataArray = orderTimeArray;
            [self presentViewController:orderTimeVC animated:true completion:^{
            }];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - Triggering Methods
- (void)clickToPopBack {
    [self.navigationController popViewControllerAnimated:true];
}

#pragma mark - Filter delegates
- (void)doneFilterWithDistrict:(NSString *)district WithRegion:(NSString *)region WithRegionCode:(NSString *)regionCode {
    districtParam = district;
    regionParam = region;
    regionCodeParam = regionCode;
    if ([district isEqual:@"不限"]) {
        area = district;
    } else {
        area = [NSString stringWithFormat:@"%@ - %@",district, region];
    }
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)didSelectedRow:(NSInteger)row WithItem:(id)item {
    if ([rentArray containsObject:item]) {
        priceParam = item;
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    } else {
        dayParam = item;
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}


- (void)clickToDismiss:(UIButton *)sender {
    [self commitToSubmitRequirement];
}

- (void)commitToSubmitRequirement {
    NSString *day = @"7";
    if ([dayParam isEqual:@"7天内"]) {
    } else if ([dayParam isEqual:@"15天内"]) {
        day = @"15";
    } else if ([dayParam isEqual:@"30天内"]) {
        day = @"30";
    } else if ([dayParam isEqual:@"2个月内"]) {
        day = @"60";
    }
    NSDictionary *params = @{@"district":districtParam, @"region":regionParam, @"regionCode":regionCodeParam, @"price":priceParam, @"day":day};
    [HttpServer putRequirementWithParas:params WithSuccessBlock:^(NSDictionary *successDic) {
        Requirement *requirement = [[Requirement alloc]initWithDic:[successDic objectForKey:@"requirement"]];
        [Utility setObject:requirement key:kRequirement];
        [self.navigationController popViewControllerAnimated:true];
    } withFailBlock:^(id failData) {
        NSLog(@"%@",failData);
        [TSMessage showNotificationInViewController:self title:@"修改需求失败!" subtitle:@"请稍后重新尝试提交新需求" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
     }];
    
}

@end
